package com.example.service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.AirspacePlan;
import com.example.entity.MicroPage;
import com.example.entity.SearchResult;
import com.example.entity.info.AirLaneInfo;
import com.example.entity.info.SpecialInfo;
import com.example.entity.info.TakeoffLandInfo;
import com.example.entity.info.WorkInfo;
import com.example.entity.transAirspacePlanning;
import com.example.mapper.AirspacePlanMapper;
import com.example.service.interfaces.AirspacePlanServiceInterface;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @program: microservice
 * @description:
 * @author: Aprilies
 * @create: 2024-09-10 16:51
 **/

@Service
public class AirspacePlanService extends ServiceImpl<AirspacePlanMapper, AirspacePlan> implements AirspacePlanServiceInterface {

    @Autowired
    private AirspacePlanMapper airspacePlanMapper;

    public List<AirspacePlan> findAll(){return airspacePlanMapper.selectList(null);}
    public Optional<AirspacePlan> findByID(Long id){return Optional.ofNullable(airspacePlanMapper.selectById(id));}

    public AirspacePlan isave(AirspacePlan user){
        airspacePlanMapper.insert(user);
        return user;
    }

    //更新除approval_status之外的信息
    public Optional<AirspacePlan> update(AirspacePlan user) {
        AirspacePlan ori = this.getById(user.getId());
        user.setId(ori.getId());  // 保持原有的 ID
        user.setApprovalStatus(ori.getApprovalStatus());

        int i = airspacePlanMapper.updateById(user);
        if(i == 1){
            return Optional.of(user);
        }
        return Optional.empty();
    }

    //双参数更新status(id,operation)
    public Optional<AirspacePlan> updateStatus(int id , Integer status) {
        UpdateWrapper<AirspacePlan> updateWrapper = new UpdateWrapper<>();
//        SysUser update = new SysUser();
        AirspacePlan update = this.getById(id);
        update.setId(id);
        update.setApprovalStatus(status);
        updateWrapper.eq("id", id).set("approval_status", status);
        int i = airspacePlanMapper.update( update, updateWrapper);
        if(i == 1){
            return Optional.of(update);
        }
        return Optional.empty();
    }


    public List<AirspacePlan> getAllUsers() {
        // 使用MyBatis Plus提供的方法查询所有用户
        return airspacePlanMapper.selectList(null);
    }


    public boolean delete(Long id) {
        if (airspacePlanMapper.selectById(id) != null) {
            airspacePlanMapper.deleteById(id);
            return true;
        }
        return false;
    }

    //信息传递预留接口
    public boolean transferInfo(int id) {
        // 根据用户ID从数据库中获取用户信息
        AirspacePlan user = airspacePlanMapper.selectById(id);

        // TODO:实现用户发布逻辑

        return true;
    }


    public SearchResult keyser(String keyword, String sort, boolean order) {
        QueryWrapper<AirspacePlan> wrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            // 模糊匹配 program_name、application_acceptance_time 和 id 字段
            wrapper.like("program_name", keyword)
                    .or()
                    .like("application_acceptance_time", keyword) // 假设 application_acceptance_time 被格式化为字符串
                    .or()
                    .like("id", keyword);
        }

        if (sort != null && !sort.isEmpty()) {
            if (order) {
                wrapper.orderByAsc(sort);
            } else {
                wrapper.orderByDesc(sort);
            }
        }

        List<AirspacePlan> list = airspacePlanMapper.selectList(wrapper);
        // 分别提取机场、航线、作业区域信息
        List<SearchResult.AirportInfo> airports = list.stream()
                .map(user -> new SearchResult.AirportInfo(user.getAirportName(), user.getAirportType(),user.getLandingZoneType(),user.getLandingLocationCoordinates()))
                .collect(Collectors.toList());

        List<SearchResult.RouteInfo> routes = list.stream()
                .map(user -> new SearchResult.RouteInfo(user.getRouteName(), user.getRouteType() , user.getCoordinateInformationPoints(), user.getHeightInterval()))
                .collect(Collectors.toList());

        List<SearchResult.OperationInfo> operationAreas = list.stream()
                .map(user -> new SearchResult.OperationInfo(user.getOperationAreaName(), user.getOperationAreaType(), user.getOperationType(), user.getCoordinateInformationPoints(), user.getHeightInterval()))
                .collect(Collectors.toList());

        List<SearchResult.SpecialInfo> specials = list.stream()
                .map(user -> new SearchResult.SpecialInfo(user.getSpecialAirspaceName(), user.getSpecialAirspaceType(), user.getCoordinateInformationPoints(), user.getHeightInterval()))
                .collect(Collectors.toList());
        // 返回结果
        return new SearchResult(list, airports, routes, operationAreas, specials, keyword, sort, order);
//        return new SearchResult(list, keyword, sort, order);
    }

    //分页搜索
    public MicroPage<AirspacePlan> page(int current, int size, AirspacePlan condition) {
//
        QueryWrapper<AirspacePlan> wrapper = new QueryWrapper<>();
        if(condition != null && condition.getApplicationId() != null){
            wrapper.like("application_id", condition.getApplicationId()).or();
        }
        if(condition != null && condition.getUserName() != null){
            wrapper.like("user_name", condition.getUserName()).or();
        }
        if(condition != null && condition.getApplicant() != null){
            wrapper.like("applicant", condition.getApplicant()).or();
        }
        Page<AirspacePlan> page = new Page<>(current, size);
        Page<AirspacePlan> sysUserPage = airspacePlanMapper.selectPage(page, wrapper);
        int total = (int)sysUserPage.getTotal();
        int pageSize = (int)page.getSize();
        MicroPage<AirspacePlan> sysUserMicroPage = new MicroPage<>();
        sysUserMicroPage.setTotal(total);
        sysUserMicroPage.setPageData(sysUserPage.getRecords());
        sysUserMicroPage.setPageNum(current);
        sysUserMicroPage.setPageSize(size);
        Integer pages = (int) Math.ceil((double) total / pageSize);
        sysUserMicroPage.setPages(pages);
        return sysUserMicroPage;
    }

    //关键字搜索搜索搜索搜索
    public List<transAirspacePlanning> conditionalSearch(String keyword, String sort, boolean order) {
        QueryWrapper<AirspacePlan> wrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            // 模糊匹配 program_name、application_acceptance_time 和 id 字段
            wrapper.like("program_name", keyword)
                    .or()
                    .like("application_acceptance_time", keyword) // 假设 application_acceptance_time 被格式化为字符串
                    .or()
                    .like("id", keyword);
        }

        if (sort != null && !sort.isEmpty()) {
            if (order) {
                wrapper.orderByAsc(sort);
            } else {
                wrapper.orderByDesc(sort);
            }
        }

        List<AirspacePlan> airspacePlannings = airspacePlanMapper.selectList(wrapper);
        return airspacePlannings.stream().map(airspacePlanning -> {
            transAirspacePlanning transresult = new transAirspacePlanning();
            BeanUtils.copyProperties(airspacePlanning, transresult);
            String landingzone = airspacePlanning.getTakeoffLandInfo();
            String airlane = airspacePlanning.getAirLaneInfo();
            String work = airspacePlanning.getWorkInfo();
            String special = airspacePlanning.getSpecialInfo();
            if(landingzone != null && !landingzone.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(landingzone);
                List<TakeoffLandInfo> landingZoneInfos = jsonArray.toJavaList(TakeoffLandInfo.class);
                transresult.setTakeoffLandInfo(landingZoneInfos);
            }

            if(airlane != null && !airlane.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(airlane);
                List<AirLaneInfo> airLaneInfos = jsonArray.toJavaList(AirLaneInfo.class);
                transresult.setAirlineInfo(airLaneInfos);
            }
            if(work != null && !work.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(work);
                List<WorkInfo> workInfos = jsonArray.toJavaList(WorkInfo.class);
                transresult.setWorkInfo(workInfos);
            }
            if(special != null && !special.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(special);
                List<SpecialInfo> speciaInfos = jsonArray.toJavaList(SpecialInfo.class);
                transresult.setSpecialInfo(speciaInfos);
            }
            return transresult;
        }).collect(Collectors.toList());
    }

}
